package com.mlink.vs.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.seasar.struts.annotation.Execute;

import com.google.gson.Gson;
import com.mlink.vs.entity.BaiduAddPointResult;
import com.mlink.vs.entity.BaiduCreatFenceResult;
import com.mlink.vs.entity.FenceAlarmListResult;
import com.mlink.vs.entity.FenceListResult;
import com.mlink.vs.entity.OrgList;
import com.mlink.vs.entity.OrgListResult;
import com.mlink.vs.entity.PiccFence;
import com.mlink.vs.entity.PiccFenceAlarm;
import com.mlink.vs.entity.PiccUser;
import com.mlink.vs.entity.SignInLinst;
import com.mlink.vs.entity.SignInRequeryResult;
import com.mlink.vs.entity.SignQueryResult;
import com.mlink.vs.service.PiccFenceAlarmService;
import com.mlink.vs.service.PiccFenceService;
import com.mlink.vs.service.PiccUserService;
import com.mlink.vs.service.PiccUserSigninService;
import com.mlink.vs.util.Constants;
import com.mlink.vs.util.StreamUtil;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;

/**
 * 围栏相关接口接口
 * 
 * @author Administrator
 */
public class FenceAction {

	/**
	 * request请求对象
	 */
	@Resource
	private HttpServletRequest req;

	/**
	 * response请求对象
	 */
	@Resource
	private HttpServletResponse rep;

	@Resource
	PiccFenceService piccFenceService;

	@Resource
	PiccUserSigninService piccUserSigninService;

	@Resource
	PiccFenceAlarmService piccFenceAlarmService;

	/**
	 * 创建围栏
	 */
	@Execute(validator = false)
	public String createFence() {
	
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		String keywords = null;
		Map<String, String> stsMap = new HashMap<String, String>();
		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		if (mapData == null) {
			return null;
		}

		String userId = (String) mapData.get("userId");
		String fenceType = (String) mapData.get("fenceType");// 0是电子围栏1 是签到围栏

		String fenceName = (String) mapData.get("fenceName");
		String monitoredPerson = (String) mapData.get("monitoredPerson");
		String vertexes = (String) mapData.get("vertexes");
		String coordType = (String) mapData.get("coordType");
		String denoise = (String) mapData.get("denoise");

		rep.setCharacterEncoding("utf-8");
		try {
			if (StringUtils.isBlank(userId)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "userId不能为空");

				rep.getWriter().println(gson.toJson(stsMap));

				rep.getWriter().flush();
				return null;
			}
			if (fenceType.equals("1")) {
				if (StringUtils.isBlank(fenceType)) {
					stsMap.put("sts", "1");
					stsMap.put("msg", "fenceType 不能为空");
					rep.getWriter().println(gson.toJson(stsMap));
					rep.getWriter().flush();
					return null;
				}
				if (StringUtils.isBlank(monitoredPerson)) {
					stsMap.put("sts", "1");
					stsMap.put("msg", "monitoredPerson 不能为空");
					rep.getWriter().println(gson.toJson(stsMap));
					rep.getWriter().flush();
					return null;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String[] mdlist = monitoredPerson.split(",");
		String fenceGroupId = UUID.randomUUID().toString().replace("-", "");
		for (int i = 0; i < mdlist.length; i++) {
			String url = "http://yingyan.baidu.com/api/v3/fence/createpolygonfence";
			HttpClient hc = new HttpClient();
			PostMethod pm = new PostMethod(url);

			pm.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

			pm.setParameter("ak", Constants.ak);
			pm.setParameter("service_id", Constants.service_id);

			pm.setParameter("fence_name", fenceName);

			pm.setParameter("monitored_person", mdlist[i]);
			pm.setParameter("vertexes", vertexes);
			pm.setParameter("coord_type", coordType);
			pm.setParameter("denoise", denoise);

			try {
				hc.executeMethod(pm);
				String ret = pm.getResponseBodyAsString();

				BaiduCreatFenceResult rresult = gson.fromJson(ret, BaiduCreatFenceResult.class);
				if (rresult.status == 0) {
					String start = null;
					String end = null;
					if (fenceType.equals("1")) {
						start = (String) mapData.get("start");
						end = (String) mapData.get("end");
					}
					PiccFence piccFence = new PiccFence();
					piccFence.id = UUID.randomUUID().toString().replace("-", "");

					piccFence.fenceGroupId = fenceGroupId;
					piccFence.userId = userId;
					piccFence.fenceId = rresult.fence_id + "";
					piccFence.fenceType = fenceType; // 0是电子围栏1 是签到围栏
					piccFence.fenceName = fenceName;
					piccFence.monitoredPerson = mdlist[i];
					piccFence.vertexes = vertexes;
					piccFence.coordType = coordType;
					piccFence.denoise = denoise;
					if (fenceType.equals("1")) {
						piccFence.signinStart = start;
						piccFence.signinEnd = end;
					}
					Timestamp timestamp = new Timestamp((new Date()).getTime());
					SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String time = formatter.format(timestamp);
					piccFence.createTime = time;
					piccFence.updateTime = time;
					piccFenceService.insert(piccFence);
				}
			} catch (HttpException e) {

				e.printStackTrace();
			} catch (IOException e) {

				e.printStackTrace();
			}
		}

		try {
			stsMap.put("sts", "0");
			stsMap.put("fenceId", fenceGroupId);
			rep.setCharacterEncoding("utf-8");
			rep.getWriter().println(gson.toJson(stsMap));
			rep.getWriter().flush();

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 获取围栏列表
	 */
	@Execute(validator = false)
	public String getFenceList() {
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);

		Map<String, String> stsMap = new HashMap<String, String>();
		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		String fenceType = null;
		if (mapData != null)
			fenceType = (String) mapData.get("fenceType");// 0是电子围栏1 是签到围栏

		try {
			List<PiccFence> pflist = piccFenceService.findAllOrderByTime(fenceType);
			List<PiccFence> rflist = new ArrayList<PiccFence>();
			for (int i = 0; i < pflist.size(); i++) {
				pflist.get(i).id = null;
				PiccFence orgPF = pflist.get(i);
				Boolean isexist = false;
				for (int j = 0; j < rflist.size(); j++) {
					PiccFence tempPF = rflist.get(j);
					if (tempPF.fenceGroupId.equals(orgPF.fenceGroupId)) {
						rflist.get(j).monitoredPerson = tempPF.monitoredPerson + "," + orgPF.monitoredPerson;
						isexist = true;
						break;
					}

				}

				if (isexist == false) {
					rflist.add(orgPF);
				}

			}

			for (int k = 0; k < rflist.size(); k++) {
				rflist.get(k).fenceId = rflist.get(k).fenceGroupId;
				rflist.get(k).fenceGroupId = null;
			}
			FenceListResult fenceListResult = new FenceListResult();
			fenceListResult.sts = "0";

			fenceListResult.list = rflist;
			rep.setCharacterEncoding("utf-8");
			rep.getWriter().println(gson.toJson(fenceListResult));
			rep.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 删除指定围栏
	 */
	@Execute(validator = false)
	public String delFence() {
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);

		Map<String, String> stsMap = new HashMap<String, String>();
		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		if (mapData == null) {
			rep.setCharacterEncoding("utf-8");
			try {
				stsMap.put("sts", "1");
				stsMap.put("msg", "必须传入参数");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		String fenceId = (String) mapData.get("fenceId");

		try {
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(fenceId)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "fenceId 不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			List<PiccFence> pf = piccFenceService.findOneOrderByTime(fenceId);

			if (pf.size() <= 0) {
				stsMap.put("sts", "0");
				rep.setCharacterEncoding("utf-8");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			String fence_ids = "";
			for (int i = 0; i < pf.size(); i++) {
				if (i == 0) {
					fence_ids = pf.get(i).fenceId;
				} else {

					fence_ids = fence_ids + "," + pf.get(i).fenceId;
				}
			}

			String url = "http://yingyan.baidu.com/api/v3/fence/delete";
			HttpClient hc = new HttpClient();
			PostMethod pm = new PostMethod(url);
			pm.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			pm.setParameter("ak", Constants.ak);
			pm.setParameter("service_id", Constants.service_id);
			pm.setParameter("fence_ids", fence_ids);

			try {
				hc.executeMethod(pm);
				String ret = pm.getResponseBodyAsString();

				BaiduCreatFenceResult rresult = gson.fromJson(ret, BaiduCreatFenceResult.class);
				if (rresult.status == 0) {

				}
			} catch (HttpException e) {

				e.printStackTrace();
			} catch (IOException e) {

				e.printStackTrace();
			}

			int result = piccFenceService.delByFenceId(fenceId);

			if (result > 0) {
				stsMap.put("sts", "0");
			} else {
				stsMap.put("sts", "1");
			}

			rep.setCharacterEncoding("utf-8");
			rep.getWriter().println(gson.toJson(stsMap));
			rep.getWriter().flush();
		} catch (

		IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 签到查询
	 */
	@Execute(validator = false)
	public String signQuery() {
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);

		Map<String, String> stsMap = new HashMap<String, String>();
		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		if (mapData == null) {
			return null;
		}

		String userId = (String) mapData.get("userId");
		String date = (String) mapData.get("date");

		String startStr = (String) mapData.get("start");
		String pageCountStr = (String) mapData.get("pageCount");
		String department = (String) mapData.get("department");

		try {
			// rep.setCharacterEncoding("utf-8");
			// if (StringUtils.isBlank(startStr)) {
			// stsMap.put("sts", "1");
			// stsMap.put("msg", "start不能为空");
			// rep.getWriter().println(gson.toJson(stsMap));
			// rep.getWriter().flush();
			// return null;
			// }
			// if (StringUtils.isBlank(pageCountStr)) {
			// stsMap.put("sts", "1");
			// stsMap.put("msg", "pageCount 不能为空");
			// rep.getWriter().println(gson.toJson(stsMap));
			// rep.getWriter().flush();
			// return null;
			// }
			// int start = Integer.parseInt(startStr);
			// int pageCount = Integer.parseInt(pageCountStr);
			rep.setCharacterEncoding("utf-8");

			List<SignInRequeryResult> signInRequeryResult = piccUserSigninService.signinByUserId(userId, date);
			List<SignInLinst> signInLinst = new ArrayList<SignInLinst>();

			for (int i = 0; i < signInRequeryResult.size(); i++) {

				Boolean isexist = false;
				for (int j = 0; j < signInLinst.size(); j++) {
					if (signInRequeryResult.get(i).getUserId().equals(signInLinst.get(j).userId)) {
						signInLinst.get(j).signinDate.add(signInRequeryResult.get(i).signinDate);
						isexist = true;
						break;
					}
				}
				if (isexist == false) {
					SignInLinst temp = new SignInLinst();
					temp.userId = signInRequeryResult.get(i).getUserId();
					temp.userCompany = signInRequeryResult.get(i).getUserCompany();
					temp.signinDate = new ArrayList<String>();
					String signinDate = signInRequeryResult.get(i).signinDate;
					temp.signinDate.add(signinDate);

					signInLinst.add(temp);
				}
			}
			SignQueryResult signQueryResult = new SignQueryResult();
			signQueryResult.sts = "0";
			signQueryResult.signInLinst = signInLinst;
			rep.setCharacterEncoding("utf-8");
			rep.getWriter().println(gson.toJson(signQueryResult));
			rep.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 获取电子围栏报警信息
	 */
	@Execute(validator = false)
	public String getFenceAlarmList() {
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);

		Map<String, String> stsMap = new HashMap<String, String>();
		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		if (mapData == null) {
			return null;
		}

		String pageNumStr = (String) mapData.get("pageNum");
		String pageCountStr = (String) mapData.get("pageCount");
		String fenceId = (String) mapData.get("fenceId");
		String userId = (String) mapData.get("userId");
		String date = (String) mapData.get("date");
		try {
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(pageNumStr)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "pageNum不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(pageCountStr)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "pageCount 不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			int pageNum = Integer.parseInt(pageNumStr);
			int pageCount = Integer.parseInt(pageCountStr);

			
			int startt = (pageNum- 1) * pageCount;
			List<PiccFenceAlarm> piccFenceAlarm = piccFenceAlarmService.findAllOrderByDate(date, startt, pageCount,
					userId, fenceId);
			int totalCount = piccFenceAlarmService.findTotalCount(date, userId, fenceId);

			String sumPage = null;

			if (totalCount % pageCount == 0) {
				sumPage = totalCount / pageCount + "";
			} else {
				sumPage = totalCount / pageCount + 1 + "";
			}

			FenceAlarmListResult fenceListResult = new FenceAlarmListResult();
			fenceListResult.sts = "0";
			fenceListResult.sumPage = sumPage+"";
			fenceListResult.totalCount = totalCount+"";

			fenceListResult.list = piccFenceAlarm;

			rep.setCharacterEncoding("utf-8");
			rep.getWriter().println(gson.toJson(fenceListResult));
			rep.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

}